package com.lglbc.day05;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Author 乐哥聊编程
 * @Doc 关注公众号"乐哥聊编程"获取文档和源码
 * @Date 2023/4/8
 * @Description
 */
@Controller
public class IndexController {
    @RequestMapping("/")
    @ResponseBody
    public String index(Authentication authentication){
        return JSON.toJSONString(authentication);
    }

    @RequestMapping("/login.html")
    public String login(){
        return "login";
    }
    @Autowired(required = false)
    private Producer producer;
    @RequestMapping("/kaptcha")
    public void kaptcha(HttpServletResponse response, HttpSession session){
        response.setContentType("image/jpg");
        String text = producer.createText();
        session.setAttribute("KAPTCHA_CODE",text);
        BufferedImage image = producer.createImage(text);
        try(ServletOutputStream outputStream = response.getOutputStream()){
            ImageIO.write(image,"jpg",outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
